package com.renren.project.admin.modules.web.app;


import com.google.common.collect.Maps;
import com.renren.project.admin.interceptors.AuthorizationInterceptor;
import com.renren.project.core.utils.JwtUtils;
import com.renren.project.core.utils.RsaUtils;
import com.renren.project.db.modules.app.form.LoginForm;
import com.renren.project.db.modules.app.service.UserService;
import com.renren.project.db.utils.R;
import com.renren.project.db.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        //用户登录
        long userId = userService.login(form);
        String token = null;
        try {
            Map<String,Object> map = Maps.newHashMap();
            map.put(AuthorizationInterceptor.USER_KEY,userId);
            PrivateKey privateKey = RsaUtils.getPrivateKey();
            // 过期时间：720小时
            //Date expireDate = DateUtils.getAfterDate(new Date(), 0, 0, 0, 720, 0, 0);
            token = jwtUtils.generateToken(map, privateKey,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        return R.ok(map);
    }

}
